package com.example.aicloud.config;

import jakarta.annotation.Resource;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.security.config.annotation.web.builders.HttpSecurity;
import org.springframework.security.config.annotation.web.configuration.EnableWebSecurity;
import org.springframework.security.config.annotation.web.configurers.AbstractHttpConfigurer;
import org.springframework.security.config.http.SessionCreationPolicy;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.security.web.SecurityFilterChain;
import org.springframework.security.web.authentication.UsernamePasswordAuthenticationFilter;

/**
 * @Description: Spring Security 框架配置
 * @Author Mr.Tang
 */
@Configuration
@EnableWebSecurity
public class SecurityConfig {

    @Resource
    private LoginAuthenticationFilter loginAuthenticationFilter;

    @Bean
    public PasswordEncoder passwordEncoder() {
        return new BCryptPasswordEncoder();
    }


    @Bean
    public SecurityFilterChain filterChain(HttpSecurity http) throws Exception {
        return http
                // 禁用明文验证
                .httpBasic(AbstractHttpConfigurer::disable)
                // 禁用 CSRF 验证
                .csrf(AbstractHttpConfigurer::disable)
                // 禁用默认的登录页面
                .formLogin(AbstractHttpConfigurer::disable)
                // 禁用默认的注销页面
                .logout(AbstractHttpConfigurer::disable)
                // 禁用默认的 Header, （支持 iframe 打开页面）
                .headers(AbstractHttpConfigurer::disable)
                // 禁用 Session(项目中使用 JWT 认证)
                .sessionManagement(session ->
                        session.sessionCreationPolicy(SessionCreationPolicy.STATELESS))
                .authorizeHttpRequests(authorize -> authorize
                        .requestMatchers(   // 允许访问的资源
                                "/layui/**",
                                "/index.html",
                                "/login.html",
                                "/reg.html",
                                "/user/login",
                                "/user/register",
                                "/captcha/getCaptcha",
                                "/tongyi/chat",
                                "/tongyi/draw",
                                "/xunfei/chat",
                                "/xunfei/draw",
                                "qianfan/chat",
                                "/qianfan/draw",
                                "/discuss/detail"

                        ).permitAll()
                        .anyRequest().authenticated()  // 其他的请求都需要进行认证拦截
                )
                // 添加 自定义登录认证过滤器
                .addFilterBefore(loginAuthenticationFilter, UsernamePasswordAuthenticationFilter.class)
                .build();
    }


}
